package CouponService

import (
	"context"
	"gdshop-back-end-go/client-api/app/request/CouponReq"
	"gdshop-back-end-go/client-api/app/response/CouponResp"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/response"
)

func Index(ctx context.Context, parames *CouponReq.Index) *response.JsonResponse {
	var res []*CouponResp.Index
	// 根据最后领取时间过滤
	whereText := " AND ( receive_time_type = 0 OR ( receive_time_type = 1 AND receive_time_end > UNIX_TIMESTAMP() ) )"
	// 固定时间段用券结束时间 过滤
	whereText += " AND ( time_type = 2 OR ( time_type = 1 AND time_end > UNIX_TIMESTAMP() ) )"
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "coupon").Where(
		"status = ?"+whereText, 2).
		Structs(&res)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	// 取出当前登陆会员的优惠券ID
	// member_id = ? AND (expires_time = 1 OR expires_time > UNIX_TIMESTAMP() )
	var mcList []*entity.MemberCoupon
	err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member_coupon").Where(
		"member_id = ?",
		parames.MemberId).Structs(&mcList)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	for _, item := range res {
		if item.ReceiveLimit < 1 {
			// 不限制领取数量
			continue
		}
		if item.ReceiveLimit > 0 {
			// 限制领取数量 大于 0，查出当前已领取多少张，如果大于等于领取限制，赋值 MyStatus = 3 否则 MyStatus = 1
			receiveNum := 0 // 领取数量
			useNum := 0     // 使用数量
			for _, mc := range mcList {
				if item.Id == mc.CouponId {
					receiveNum++
					if mc.UseTime > 0 {
						useNum++
					}
				}
			}
			// 已使用数量大于等于限制数量，不可领取
			if useNum >= item.ReceiveLimit {
				item.MyStatus = 3
			} else {
				// 尽量引导用户每次只领取一张，使用后再次领取
				// 如果领取数量大于 使用数量，返回去使用
				if receiveNum > useNum {
					item.MyStatus = 1
				}
			}
		}
	}

	return response.SuccessByRequestMessageData(nil, "成功", res)
}
